﻿#include "itemadd.h"
#include "ui_itemadd.h"

ItemAdd::ItemAdd(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ItemAdd)
{
    ui->setupUi(this);
}

ItemAdd::~ItemAdd()
{
    delete ui;
}

bool ItemAdd::addItem(const QString &label, const QString &alias, const QString &hexcode, int code, const QString &detail, const QString &addition)
{
    QSqlQuery query;
    query.prepare(QString("insert into %1 (label,alias,hexcode,code,detail,addition) values (?,?,?,?,?,?)").arg(TD_CMD));
    query.addBindValue(label);
    query.addBindValue(alias);
    query.addBindValue(hexcode);
    query.addBindValue(code);
    query.addBindValue(detail);
    query.addBindValue(addition);

    if(query.exec())
        return true;
    else
    {
        qDebug() << query.lastError().text();
        return false;
    }
}

void ItemAdd::on_btn_submit_clicked()
{
    QString label=ui->label->text().trimmed();
    if(label.isEmpty())
        return;

    QString alias=ui->alias->text().trimmed();

    QString hexcode=ui->hexcode->text().trimmed();
    if(hexcode.isEmpty())
        return;

    bool ok;
    uint code=hexcode.toUInt(&ok,16);
    if(ok)
    {
        if(code < 16)
        {
            QMessageBox::warning(this,QStringLiteral("数值范围错误"),QStringLiteral("不得小于0x10！"));
            ui->hexcode->clear();
            return;
        }
        QString detail=ui->detail->text().trimmed();
        QString addition=ui->addition->text().trimmed();
        if(!addItem(label,alias,hexcode,code,detail,addition))
            QMessageBox::warning(this,QStringLiteral("异常情况"),QStringLiteral("无法提交数据！"));
        else
            accept();
    }
    else
    {
        QMessageBox::critical(this,QStringLiteral("输入错误"),QStringLiteral("无法识别，请重新输入"));
        ui->hexcode->clear();
    }
}
